package org.osll.tictactoe.transport.tcp.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.osll.tictactoe.Control;
import org.osll.tictactoe.ServerConnection;
import org.osll.tictactoe.Team;
import org.osll.tictactoe.transport.tcp.LoginAcceptedResponse;
import org.osll.tictactoe.transport.tcp.LoginQuery;
import org.osll.tictactoe.transport.tcp.server.SocketProcessor;

public class ServerConnectionImpl extends SocketProcessor implements ServerConnection {

	private String host = null;
	private int port = 0;
	
	public ServerConnectionImpl(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	@Override
	public Control connect(String userName, Team team) {
		Socket socket;
		try {
			socket = new Socket(host,port);
		} catch (UnknownHostException e) {
			throw new IllegalStateException("Host is unknown");
		} catch (IOException e) {
			throw new IllegalStateException("Couldn't connect to host");
		}
		
		LoginQuery query = new LoginQuery();
		query.setName(userName);
		query.setTeam(team);
		
		write(socket,query);
		
		LoginAcceptedResponse response = (LoginAcceptedResponse)read(socket);
		System.out.println("[TCP client] Try to connect control to " + host + ":" + response.getPort());
		Control c = null;
		try {
			 c = new ControlImpl(host,response.getPort(), userName, team);
		} catch (IOException e) {
			throw new IllegalStateException("Couldn't connect to Control server"); 
		}
		return c;
	}

}
